<?php

namespace App\Admin\Controllers;

use App\Models\Misdeed;
use App\Models\WorkUser;
use App\Models\Engineering;
use App\Models\Company;
use App\Models\Team;
use Carbon\Carbon;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use App\Admin\Forms\ImportForm;
use App\Admin\Actions\DownloadTemplate;
use Dcat\Admin\Widgets\Modal;
use Dcat\Admin\Widgets\Card;
use App\Admin\Renderable\WorkUserDetails;
use App\Admin\Renderable\WorkUserHistoryDetails;
use App\Admin\Extensions\ExcelExpoter;
use App\Models\TypeWork;


class NormalWorkUserController extends AdminController
{

    protected $title = '在职务工人员';
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WorkUser(), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->export()->disableExportAll();
            $grid->perPages([10, 20, 30, 40, 50,100,200,300,400,500]);

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('engineering', '所属工程')->select(function ($status){
                    $Adminid  = Admin::user()->id;
                    if($Adminid != 1 && Admin::user()->whole != 0){
                        $engineering_name = DB::table('engineering')->where('manager','like','%'.$Adminid.'%')->where('deleted_at',null)->pluck('engineering_name');
                    }else{
                        $engineering_name = DB::table('engineering')->where('deleted_at',null)->pluck('engineering_name');
                    }
                    $arr = [];
                    foreach ($engineering_name as $key => $value){
                        $arr["$value"] = $value;
                    }
                    return $arr;
                })->width(5);
                $filter->like('id_card', '身份证号')->width(5);
                $filter->like('name', '姓名')->width(5);
                $filter->equal('mobile','手机号')->width(5);


//                $filter->like('team', '队伍(模糊查询)')->width(5);
//
//                $filter->like('team', '所属队伍')->select(function ($team){
//                    $name = DB::table('team')->where('deleted_at',null)->pluck('name');
//                    $arr = [];
//                    foreach ($name as $key => $value){
//                        $arr["$value"] = $value;
//                    }
//                    return $arr;
//                })->width(5);

                $filter->group('team', function ($group) {
                    $group->like('模糊查找');
                    $group->equal('精确查找');
                },'所属队伍')->width(5);


                $filter->like('company', '所属公司')->select(function ($team){
                    $name = DB::table('company')->where('deleted_at',null)->pluck('name');
                    $arr = [];
                    foreach ($name as $key => $value){
                        $arr["$value"] = $value;
                    }
                    return $arr;
                })->width(5);

                $filter->equal('type_work','工种')->select(function ($team){
                    $name = DB::table('type_work')->pluck('name');
                    $arr = [];
                    foreach ($name as $key => $value){
                        $arr["$value"] = $value;
                    }
                    return $arr;
                })->width(5);

                $filter->equal('position','职务')->select(['一般工人', '班组长', '其他'])->width(5);

                $filter->between('enter_time', '入职时间')->date()->width(5);

            });

            if (Admin::user()->can('inspector')) {
                $grid->tools(function (Grid\Tools $tools) {
                    $tools->append(Modal::make()
                        // 大号弹窗
                        ->lg()
                        // 弹窗标题
                        ->title('上传文件')
                        // 按钮
                        ->button('<button class="btn btn-primary"><i class="feather icon-upload"></i> 导入新进人员数据</button>')
                        // 弹窗内容
                        ->body(ImportForm::make()));
                    // 下载导入模板
                    $tools->append(DownloadTemplate::make()->setKey('test_question'));
                });
            }



            if(Admin::user()->sensitive == 0){
                $grid->export(new ExcelExpoter());
            }


            $Adminid  = Admin::user()->id;
            if(Admin::user()->whole == 1){
                $engineering_names = DB::table('engineering')->where('manager','like','%'.$Adminid.'%')->pluck('engineering_name');
                $grid->model()->whereIn('engineering', $engineering_names);
            }
            if(Admin::user()->whole == 2){
                $grid->model()->where('uploader', $Adminid);
            }


            $grid->model()->where('status', 1)->where('misdeed', 1);

            $grid->number('序号');
//            $grid->column('name');

            $grid->column('name','姓名')->display(function ($name) {
                $res = false;
                if (str_contains($this->photo_portrait, 'jpeg') || str_contains($this->photo_portrait, 'png') || str_contains($this->photo_portrait, 'jpg')) {
                    $res = true;
                }
                if(!$res){
                    return "<span style='color:red'>$name.（缺少身份证正面照）</span>";
                }
                if(empty($this->bank_number)){
                    return "<span style='color:red'>$name.（缺少银行卡号）</span>";
                }
                return $name;
            });


            $grid->column('company','所属公司');
            $grid->column('team','所属队伍');
            $grid->column('engineering','所属工程')->limit(10);

//            $grid->column('sex')->display(function ($sex) {
//                if($sex == 1){
//                    return "<span style='color:blue'>男</span>";
//                }else{
//                    return "<span style='color:red'>女</span>";
//                }
//            });

//            $grid->column('status','状态')->display(function ($status) {
//                if($status == 1){
//                    return "<span style='color:blue'>正常</span>";
//                }else{
//                    return "<span style='color:red'>离职</span>";
//                }
//            });
//            $grid->column('misdeed','不端行为')->display(function ($misdeed) {
//                if($misdeed == 1){
//                    return "<span style='color:green'>无</span>";
//                }else{
//                    return DB::table('misdeed')->where('id',$misdeed)->value('name');
//                }
//            });

            $grid->column('type_work','工种');
            $grid->column('position','职务')->select(['一般工人', '班组长', '其他']);
            $grid->column('age','年龄');
            $grid->column('uploader','数据来源')->display(function ($uploader) {
                return DB::table('admin_users')->where('id',$uploader)->value('username');
            });
//            $grid->column('id_card',"身份证号")->display(function ($id_card) {
//                if(Admin::user()->sensitive != 0){
//                    return "<span style='color:red'>您无权查看敏感信息</span>";
//                }else{
//                    return "<span style='color:green'>$id_card</span>";
//                }
//            });
//            $grid->column('mobile',"手机号")->display(function ($mobile) {
//                if(Admin::user()->sensitive != 0){
//                    return "<span style='color:red'>您无权查看敏感信息</span>";
//                }else{
//                    return "<span style='color:green'>$mobile</span>";
//                }
//            });

              if(Admin::user()->sensitive == 0){
                  $grid->column('人员详情')->display('人员详情')->modal(function (Grid\Displayers\Modal $modal) {
                      $modal->title('人员详情');
                      $modal->icon('feather icon-edit');
                      return WorkUserDetails::make()->payload(['id_card' => $this->id_card]);
                  });

                  $grid->column('人员轨迹')->display('人员轨迹')->modal(function (Grid\Displayers\Modal $modal) {
                      $modal->title('人员轨迹');
                      $modal->icon('feather icon-edit');
                      return WorkUserHistoryDetails::make()->payload(['id_card' => $this->id_card]);
                  });

              }




//            $grid->column('notes');


//            $grid->column('nationality');
//            $grid->column('registered_residence');
//            $grid->column('educational');
//            $grid->column('employment_method');
//            $grid->column('marital');
//            $grid->column('emergency_contact');
//            $grid->column('emergency_contact_mobile');
//            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WorkUser(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('photo');
            $show->field('id_card');
            $show->field('sex');
            $show->field('nationality');
            $show->field('engineering');
            $show->field('registered_residence');
            $show->field('mobile');
            $show->field('educational');
            $show->field('employment_method');
            $show->field('marital');
            $show->field('emergency_contact');
            $show->field('emergency_contact_mobile');
            $show->field('status');
            $show->field('misdeed');
            $show->field('notes');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WorkUser(), function (Form $form) {

            $form->tab('基本信息', function (Form $form) {
                $form->select('company','所属公司')->options(function ($id) {
                    return Company::where('name','<>','')->pluck('name', 'name');
                });
                $form->select('team','所属队伍')->options(function ($id) {
                    return Team::where('name','<>','')->pluck('name', 'name');
                });
                $form->select('engineering','所属工程')->options(function ($id) {
                    return Engineering::where('engineering_name','<>','')->pluck('engineering_name', 'engineering_name');
                });
                $form->text('name','姓名');
                $form->mobile('mobile','手机号')->type("number")->required();
                $form->select('type_work','工种')->options(function ($id) {
                    return TypeWork::pluck('name', 'name');
                });
                $form->select('position','职务')->options(['一般工人', '班组长', '其他']);
                $form->datetime('enter_time','入职时间')->format('YYYY-MM-DD')->required();
//                $form->datetime('exit_time','离职时间')->format('YYYY-MM-DD');
                $form->hidden('enter_date');
                $form->text('notes','备注');
            })->tab('身份证', function (Form $form) {
                $form->image('photo_portrait','身份证人像面')->move('photo/')->autoUpload();
                $form->image('photo_emblem','身份证国徽面')->move('photo/')->autoUpload();
                $form->text('id_card','身份证号')->required();
                $form->text('registered_residence','户口所在地');
                $form->text('bank_deposit','开户银行');
                $form->text('bank_number','银行卡号');
            })->tab('人员状态', function (Form $form) {
//                $form->radio('status','是否离职')->options(['1' => '正常', '2'=> '离职'])->default('1');

                $form->radio('status','是否离职')
                    ->when([2], function (Form $form) {
                        $form->datetime('exit_time','离职时间')->format('YYYY-MM-DD');
                    })
                    ->options([
                        1 => '正常',
                        2 => '离职'
                    ])
                    ->default(1);




                if (Admin::user()->can('lingdao')) {
                    $form->select('misdeed','不端行为')->options('misdeed_list');
                }

                $form->hidden('uploader');
            });


            //                $form->datetime('exit_time','离职时间')->format('YYYY-MM-DD');
//            $form->text('emergency_contact','紧急联系人');
//            $form->mobile('emergency_contact_mobile','紧急联系人手机号')->type("number");
//            $form->text('type_work','工种');
//            $form->display('created_at');
//            $form->display('updated_at');
            //                $form->select('nationality','民族')->options([ '1' => '汉族',
//                                                                            '2'=> '壮族',
//                                                                            '3'=> '满族',
//                                                                            '4'=> '回族',
//                                                                            '5'=> '苗族',
//                                                                            '6'=> '维吾尔族',
//                                                                            '7'=> '土家族',
//                                                                            '8'=> '彝族',
//                                                                            '9'=> '蒙古族',
//                                                                            '10'=> '藏族',
//                                                                         ])->default('1');
            //                $form->radio('sex')->options(['1' => '男', '2'=> '女'])->default('1');
            //                $form->radio('marital')->options(['1' => '未婚', '2'=> '已婚'])->default('1');
//                $form->select('educational','学历')->options(['1' => '高中', '2'=> '大专', '3'=> '本科'])->default('1');

            $form->saving(function (Form $form) {
                $form->enter_date = Carbon::parse($form->enter_time)->format('Y-m');

                if(!empty($form->id_card)){
                    $cf = DB::table('work_user')->where('id_card',$form->id_card)->where('deleted_at',null)->first();
                    if ($form->isCreating()) {
                        $Adminid  = Admin::user()->id;
                        $form->uploader = $Adminid;
                        if($cf != null && $cf->status != 2){
                            return $form->response()->error('该人员已在其他工程入职,在职工程为:'.$cf->engineering);
                        }
                        if($cf != null && $cf->misdeed != 0){
                            return $form->response()->error('该人员存在不端行为,行为发生工程为:'.$cf->engineering);
                        }
                        if($cf == null && $form->status == 2){
                            return $form->response()->error('该人员首次入职，不可以标注为离职状态');
                        }

                        $history = [];
                        $history['name'] = $form->name;
                        $history['id_card'] = $form->id_card;
                        $history['engineering'] = $form->engineering;
                        $history['type'] = 1;
                        $history['details'] = '首次入职';
                        $history['enter_time'] = $form->enter_time;
                        $history['created_at'] = Carbon::now();
                        DB::table('work_user_history')->insert($history);
                    }else{

                        if($cf->status == 1 && $cf->engineering != $form->engineering){
                            return $form->response()->error('该人员尚未离职，不可修改所属工程,在职工程为:'.$cf->engineering);
                        }

                        if($form->status == 2){ //更改离职状态时
                            if($form->exit_time == null){
                                return $form->response()->error('进行离职时,离职时间不能为空');
                            }
                            $history = [];
                            $history['name'] = $form->name;
                            $history['id_card'] = $form->id_card;
                            $history['engineering'] = $form->engineering;
                            $history['type'] = 2;
                            $history['details'] = '离职';
                            $history['exit_time'] = $form->exit_time;
                            $history['created_at'] = Carbon::now();
                            DB::table('work_user_history')->insert($history);
                        }

                        if($form->misdeed != 1){ //存在劣迹时
                            $history = [];
                            $history['name'] = $form->name;
                            $history['id_card'] = $form->id_card;
                            $history['engineering'] = $form->engineering;
                            $history['type'] = 4;
                            $history['details'] = $form->misdeed;
                            $history['enter_time'] = $form->enter_time;
                            $history['created_at'] = Carbon::now();
                            $history['exit_time'] = Carbon::now();
                            DB::table('work_user_history')->insert($history);
                        }

                    }
                }

            });


            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                foreach ($data as $key => $value){
                    DB::table('work_user_history')->where('id_card',$value['id_card'])->update(['deleted_at'=>Carbon::now()]);
                }
                // 通过 $result 可以判断数据是否删除成功
                if (!$result) {
                    return $form->response()->error('数据删除失败');
                }

                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });


            if (request()->getMethod() == 'PUT') {
                if (!$this->isValidID($form->id_card) && !empty($form->id_card)) {
                    $form->responseValidationMessages('id_card', '身份证号格式错误');
                }
            }

        });
    }

    function isValidID($id) {
        // 验证18位身份证号码
        $pattern18 = '/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))((0[1-9])|([1-2][0-9])|30|31)\d{3}(\d|X)$/i';
        // 验证15位身份证号码
        $pattern15 = '/^[1-9]\d{5}\d{6}(\d{3})$/';

        if (preg_match($pattern18, $id) || preg_match($pattern15, $id)) {
            return true;
        } else {
            return false;
        }
    }
}
